package com.shike.core.annotation.support;

import com.shike.core.dto.JwtUserDto;
import com.shike.core.utils.JWTUtil;
import com.shike.core.annotation.LoginUser;
import com.shike.core.utils.SysCode;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	/**
	 * 判断方法是否需要用户参数
	 * @param parameter
	 * @return
	 */
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(JwtUserDto.class)
				&& parameter.hasParameterAnnotation(LoginUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request,
                                  WebDataBinderFactory factory) throws Exception {

		String token = request.getHeader(SysCode.TOKEN);
		JwtUserDto jwtUser = JWTUtil.getJwtUser(token);
		return jwtUser;
	}
}
